from flask import jsonify, session, request, render_template

from models import db
from models.index import User
from . import user_blu


@user_blu.route("/user/center")
def user_center():
    return render_template('user.html')


@user_blu.route("/user/user_base_info")
def user_base_info():
    return render_template("user_base_info.html")


@user_blu.route("/user/basic", methods=['POST'])
def user_basic():
    # 获取用户的信息
    nick_name = request.json.get("nick_name")
    address = request.json.get("address")
    phone = request.json.get("phone")
    gender = request.json.get("gender")
    print(nick_name, address, phone, gender)
    user_id = session.get("user_id")
    print(user_id)

    user = db.session.query(User).filter(User.user_id == user_id).first()
    if not user:
        ret = {
            "errno": 4002,
            "errmsg": "没有此用户"
        }

        return jsonify(ret)

    user.nick_name = nick_name
    user.address = address
    user.phone = phone
    user.gender = gender

    db.session.commit()

    ret = {
        "errno": 0,
        "errmsg": "修改成功"
    }
    return jsonify(ret)


@user_blu.route("/user/user_pass_info")
def user_pass_info():
    return render_template("user_pass_info.html")


@user_blu.route("/user/password", methods=['POST'])
def user_password():
    # 获取浏览器收到的数据
    new_password = request.json.get("new_password")
    old_password = request.json.get("old_password")

    # 查询数据库判断原密码是否一致
    user = db.session.query(User).filter(User.password_hash == old_password).first()
    # 如果相同就修改
    if user:
        user.password_hash = new_password
        db.session.commit()
        ret = {
            "errno": 0,
            "errmsg": "修改成功"
        }
    else:
        ret = {
            "errno": 4004,
            "errmsg": "原密码错误"
        }
    # 返回json数据
    return jsonify(ret)
